<template>
  <div class="app-container">
    <!-- 导航栏 -->
    <div class="nav">
      <router-link to="/dashboard/dash" class="nav-link"><span>首页</span></router-link>
      <router-link :to="{ 
        name: 'Dashboard',
        params: { 
          standardName: standardName 
        }
      }" class="nav-link">
        <span>/</span><span>{{ standardName }}</span>
      </router-link>
      <span>/</span><span class="current-page">样品查看</span>
      <div class="nav-back">
        <el-button type="text" @click="handleBack">
          <i class="el-icon-arrow-left"></i> 返回
        </el-button>
      </div>
    </div>

    <div class="top-container">
      <!-- 搜索框 -->
      <el-input
        v-model="searchQuery"
        placeholder="搜索样品名称或生产厂家"
        style="width: 200px"
        class="filter-item"
        prefix-icon="el-icon-search"
        @input="handleSearch"
      />
      <!-- 按钮组 -->
      <div class="button-group">
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete">批量删除</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
        <el-upload
          class="upload-button"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeUpload"
          accept=".xlsx,.xls"
        >
          <el-button type="success" icon="el-icon-upload2">导入Excel</el-button>
        </el-upload>
      </div>
    </div>
    <!-- 样品清单表格 -->
    <div class="table-container">
      <el-table
        :data="paginatedData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="spId"
          label="序号"
          width="80"
        />
        <el-table-column
          prop="spName"
          label="样品名称"
        />
        <el-table-column
          prop="spFactory"
          label="生产厂家"
        />
        <el-table-column
          prop="spGg"
          label="规格型号"
        />
       
        <el-table-column
          label="操作"
          width="150"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              style="color: #67C23A"
              @click="handleEdit(scope.row)"
            >
              修改
            </el-button>
            <el-button
              type="text"
              size="small"
              style="color: #F56C6C"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page.sync="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredTableData.length"
        />
      </div>
    </div>
    <!-- 添加/修改样品弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" ref="form" :rules="rules" label-width="100px">
        <el-form-item label="样品名称" prop="spName">
          <el-input v-model="form.spName" placeholder="请输入样品名称"></el-input>
        </el-form-item>
        <el-form-item label="生产厂家" prop="spFactory">
          <el-input v-model="form.spFactory" placeholder="请输入生产厂家"></el-input>
        </el-form-item>
        <el-form-item label="规格型号" prop="spGg">
          <el-input v-model="form.spGg" placeholder="请输入规格型号"></el-input>
        </el-form-item>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'SampleCheck',
  data() {
    return {
      searchQuery: '',
      dialogVisible: false,
      dialogTitle: '添加样品',
      currentId: null,
      selectedRows: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/api/samples/import',
      tableData: [], // 初始化为空数组
      currentPage: 1,
      pageSize: 10,
      form: {
        sampleName: '',
        manufacturer: '',
        specification: '',
        batchNumber: ''
      },
      rules: {
        sampleName: [{ required: true, message: '请输入样品名称', trigger: 'blur' }],
        manufacturer: [{ required: true, message: '请输入生产厂家', trigger: 'blur' }]
      },
      standardName: '', // 添加标准名称
      projectId: null,
      staId: null,
    }
  },
  created() {
    // 从路由参数中获取所需数据
    const { param, standardName, staId } = this.$route.params;
    
    this.projectId = param;
    this.standardName = standardName || '未知标准';
    this.staId = staId;
    
    this.fetchData();
  },
  computed: {
    filteredTableData() {
      if (!this.searchQuery) return this.tableData
      return this.tableData.filter(data => {
        return ['sampleName', 'manufacturer'].some(key => {
          return String(data[key])
            .toLowerCase()
            .includes(this.searchQuery.toLowerCase())
        })
      })
    },
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = this.currentPage * this.pageSize
      const data = this.filteredTableData.slice(start, end)
      console.log('Paginated Data:', data) // 调试用
      return data
    }
  },
  methods: {
    async fetchData() {
      try {
        const res = await axios({
          url: 'http://localhost:8081/getSamples', // 确保 URL 正确
          method: 'get',
          params: {
            staId: this.$route.params.param // 确保参数名正确
          }
        })
        console.log('Fetched Data:', res.data) // 调试用
        this.tableData = res.data
      } catch (error) {
        this.$message.error('获取数据失败：' + error.message)
      }
    },
    handleSearch() {
      this.currentPage = 1
    },
    handleSelectionChange(val) {
      this.selectedRows = val
    },
    handleAdd() {
      this.dialogVisible = true
      this.dialogTitle = '添加样品'
      this.currentId = null
      this.form = {
        sampleName: '',
        manufacturer: '',
        specification: '',
        batchNumber: ''
      }
    },
    async handleEdit(row) {
      this.dialogVisible = true
      this.dialogTitle = '修改样品'
      this.currentId = row.spId
      this.form = { ...row }
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该样品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await axios({
          url: `http://localhost:8081/deleteSample/${row.spId}`, // 确保 URL 正确
          method: 'delete'
        })
        this.$message.success('删除成功')
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败：' + error.message)
        }
      }
    },
    async handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要删除的样品')
        return
      }
      try {
        await this.$confirm(`确认删除选中的 ${this.selectedRows.length} 个样品吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const deletePromises = this.selectedRows.map(row => {
          return axios({
            url: `http://localhost:8081/deleteSample/${row.spId}`, // 确保 URL 正确
            method: 'delete'
          })
        })
        await Promise.all(deletePromises)
        this.$message.success('批量删除成功')
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('批量删除失败：' + error.message)
        }
      }
    },
    async handleUploadSuccess(response) {
      try {
        await axios({
          url: 'http://localhost:8081/import/confirm', // 确保 URL 正确
          method: 'post',
          data: {
            fileUrl: response.url,
            staId: this.$route.params.standardId, // 确保参数名正确
            projectId: this.$route.params.projectId
          }
        })
        this.$message.success('Excel导入成功')
        this.fetchData()
      } catch (error) {
        this.$message.error('导入失败：' + error.message)
      }
    },
    handleUploadError(error) {
      this.$message.error('Excel导入失败：' + error.message)
    },
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.ms-excel' ||
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isExcel) {
        this.$message.error('只能上传 Excel 文件!')
        return false
      }
      return true
    },
    async submitForm() {
      try {
        await this.$refs.form.validate()
        const data = {
          ...this.form,
          staId: this.$route.params.param,
          projectId: this.$route.params.projectId
        }
        if (this.currentId) {
          // 更新样品
          await axios({
            url: `http://localhost:8081/apdateSample/${this.currentId}`, // 确保 URL 正确
            method: 'put',
            data
          })
          this.$message.success('修改成功')
        } else {
          // 添加样品
          await axios({
            url: 'http://localhost:8081/addSample', // 确保 URL 正确
            method: 'post',
            data
          })
          this.$message.success('添加成功')
        }
        this.dialogVisible = false
        this.fetchData()
      } catch (error) {
        this.$message.error(error.message || '操作失败')
      }
    },
    // 新增方法：处理当前页变化
    handleCurrentChange(page) {
      this.currentPage = page
    },
    // 新增方法：处理每页显示数量变化
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1 // 可选：切换每页数量时重置到第一页
    },
    handleBack() {
      this.$router.push({
        name: 'Dashboard',
        params: { 
          standardName: this.standardName
        }
      });
    }
  }
}
</script>



<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.top-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.button-group {
  margin: 20px 0;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.el-table {
  margin-top: 20px;
}

 /* Start of Selection */
    .filter-item {
      margin-bottom: 10px;
    }
    
    .filter-item .el-input__inner {
      border-radius: 20px;
    }
    
    .el-dialog .el-form-item {
      margin-bottom: 20px;
    }

/* 导航栏样式 */
.nav {
  padding: 20px;
  background-color: #f5f7fa;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  margin-bottom: 20px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  position: relative;
}

.nav-link {
  text-decoration: none;
  color: #909399;  /* 非当前页面使用灰色 */
  font-size: 16px;
  transition: color 0.3s;  /* 添加颜色过渡效果 */
}

.nav-link:hover {
  color: #409EFF;  /* 鼠标悬停时变为蓝色 */
}

.nav span {
  color: #909399;  /* 分隔符使用灰色 */
  font-size: 16px;
  margin: 0 5px;
}

.current-page {
  color: #409EFF !important;  /* 当前页面使用蓝色 */
  font-weight: 500;  /* 当前页面加粗 */
}

.nav-back {
  position: absolute;
  right: 20px;
}

.nav-back .el-button {
  font-size: 14px;
  color: #909399;  /* 返回按钮使用灰色 */
}

.nav-back .el-button:hover {
  color: #409EFF;  /* 鼠标悬停时变为蓝色 */
}

.nav-back i {
  margin-right: 5px;
}
</style>
